package com.tcp2.net;


import com.tcp2.msg.PushProtoMsg;
import com.tcp2.server.DxsConfig;
import com.tcp2.server.ProtoMsg;
import com.tcp2.util.ProtoUtil;
import com.yaxon.vndp.common.util.CodecUtils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Author: 杨俊辉
 * Time: 2014-12-08 17:16
 * Copyright (C) 2014 Xiamen Yaxon Networks CO.,LTD.
 */

/**
 * 上行数据接收处理，满足条件下发送redis广播到809客户端
 */

@ChannelHandler.Sharable
public class UpDataHandler extends ChannelInboundHandlerAdapter {

    protected static Logger logger = LoggerFactory.getLogger(UpDataHandler.class);

    private DxsConfig dxsConfig;


    public UpDataHandler(DxsConfig dxsConfig) {
        this.dxsConfig = dxsConfig;

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //赋值与809客户端交互的协议信息对象
        ProtoMsg m = (ProtoMsg) msg;
        PushProtoMsg targetMsg = new PushProtoMsg();
        targetMsg.msgSn = m.msgSn;
        targetMsg.msgId = m.msgId;
        ByteBuf buf = m.msgData.copy(0, m.msgData.readableBytes());
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        System.out.println("消息id:"+CodecUtils.shortToHex((short) m.msgId)+",字节数："+bytes.length);
        targetMsg.msgData = bytes;
        super.channelRead(ctx, msg);
        String msgId2Hex = CodecUtils.shortToHex((short) m.msgId);

        //车辆动态信息数据交换、报警信息
        if (msgId2Hex.equals("1200") || msgId2Hex.equals("1400")) {
            ByteBuf data = Unpooled.buffer(bytes.length);
            data.writeBytes(bytes);
            String lpn = ProtoUtil.readOctetString(data, 21);
            byte color = data.readByte();
            int dataType = data.readUnsignedShort(); //数据类型
            String topic;
            topic = "im:dxc:t9." + CodecUtils.shortToHex((short) dataType) + ":" + lpn + ":" + color;
            doUpMsgToRedis(topic, targetMsg);
        }
    }


    /**
     * 上行消息发送到Redis广播
     *
     * @param topic 发布主题
     * @param msg   协议消息
     */
    private void doUpMsgToRedis(String topic, PushProtoMsg msg) {
        try {

        } catch (Exception e) {
            logger.warn("往Redis发布主链路动态信息交换消息异常,topic:{},", topic, e);
        }

    }


}
